package com.java.common.utils;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.QuadCurve2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;

import org.springframework.util.FastByteArrayOutputStream;

/**
 * 图形验证码工具类
 * 
 * @author yilabao
 * @date 2021年3月26日
 */
public class CaptchaKit {

    private static final Random RANDOM = new Random(System.nanoTime());

    private static final int WIDTH = 108, HEIGHT = 40;

    private static final char[] CHARARRAY = "3456789ABCDEFGHJKMNPQRSTUVWXY".toCharArray();

    private static final Font[] RANDOM_FONT = new Font[] { new Font(Font.DIALOG, Font.BOLD, 33),
            new Font(Font.DIALOG_INPUT, Font.BOLD, 34), new Font(Font.SERIF, Font.BOLD, 33),
            new Font(Font.SANS_SERIF, Font.BOLD, 34), new Font(Font.MONOSPACED, Font.BOLD, 34) };

    /**
     * 生成验证码
     * 
     * @author yilabao
     * @date 2021年3月26日
     * @param captchaValue 验证码随机字符串
     * @return FastByteArrayOutputStream
     */
    public static FastByteArrayOutputStream createCaptcha(String captchaValue) {
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            drawGraphic(captchaValue, image);

            ImageIO.write(image, "jpeg", os);
        } catch (IOException e) {
        }
        return os;
    }

    /**
     * 生成验证码并输出文件
     * 
     * @author yilabao
     * @date 2021年3月26日
     * @param captchaValue 验证码随机字符串
     * @param fileName     保存图片绝对路径
     */
    public static void createCaptchaFile(String captchaValue, String fileName) {
        FastByteArrayOutputStream os = createCaptcha(captchaValue);
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(os.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 生成随机字符串
     */
    public static String getRandomString() {
        char[] randomChars = new char[4];
        for (int i = 0; i < randomChars.length; i++) {
            randomChars[i] = CHARARRAY[RANDOM.nextInt(CHARARRAY.length)];
        }
        return String.valueOf(randomChars);
    }

    private static void drawGraphic(String randomString, BufferedImage image) {
        // 获取图形上下文
        Graphics2D g = image.createGraphics();

        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        // 图形抗锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 字体抗锯齿
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // 设定背景色
        g.setColor(getRandColor(210, 250));
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 绘制小字符背景
        Color color = null;
        int drawTimes = 20;
        for (int i = 0; i < drawTimes; i++) {
            color = getRandColor(120, 200);
            g.setColor(color);
            String rand = String.valueOf(CHARARRAY[RANDOM.nextInt(CHARARRAY.length)]);
            g.drawString(rand, RANDOM.nextInt(WIDTH), RANDOM.nextInt(HEIGHT));
            color = null;
        }

        // 设定字体
        g.setFont(RANDOM_FONT[RANDOM.nextInt(RANDOM_FONT.length)]);
        // 绘制验证码
        for (int i = 0; i < randomString.length(); i++) {
            // 旋转度数 最好小于45度
            int degree = RANDOM.nextInt(28);
            if (i % 2 == 0) {
                degree = degree * (-1);
            }
            // 定义坐标
            int x = 22 * i, y = 21;
            // 旋转区域
            g.rotate(Math.toRadians(degree), x, y);
            // 设定字体颜色
            color = getRandColor(20, 130);
            g.setColor(color);
            // 将认证码显示到图象中
            g.drawString(String.valueOf(randomString.charAt(i)), x + 8, y + 10);
            // 旋转之后，必须旋转回来
            g.rotate(-Math.toRadians(degree), x, y);
        }
        // 图片中间曲线，使用上面缓存的color
        g.setColor(color);
        // width是线宽,float型
        BasicStroke bs = new BasicStroke(3);
        g.setStroke(bs);
        // 画出曲线
        QuadCurve2D.Double curve = new QuadCurve2D.Double(0d, RANDOM.nextInt(HEIGHT - 8) + 4, WIDTH / 2, HEIGHT / 2,
                WIDTH, RANDOM.nextInt(HEIGHT - 8) + 4);
        g.draw(curve);
        // 销毁图像
        g.dispose();
    }

    /**
     * 给定范围获得随机颜色
     */
    private static Color getRandColor(int fc, int bc) {
        Random random = new Random();
        int max = 255;
        if (fc > max) {
            fc = max;
        }
        if (bc > max) {
            bc = max;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

}
